/* eslint-disable no-constant-condition */
import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'

import Icon from '@/components/Icon'
import CommentItem from './components/CommentItem'
import CommentFooter from './components/CommentFooter'
import useInitialState from '@/hooks/useInitialState'
import { getArticleDetail, getCommentList } from '@/store/actions/articleDetail'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import { newDayjs } from '@/utils'
import DOMPurify from 'dompurify'
import { useEffect, useRef, useState } from 'react'

const Article = () => {
  const history = useHistory()
  const { id } = useParams<{ id: string }>()
  const [isShowAuthor,setIsShowAuthor]=useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const wrapRef = useRef<HTMLDivElement>(null)
  const { info: article } = useInitialState(() => getArticleDetail(id), 'articleDetail')
  useInitialState(() => getCommentList(id), 'articleDetail')

  useEffect(() => { //代码高亮
    hljs.configure({
      //  忽略未经转义的html字符
      ignoreUnescapedHTML: true
    })
    const codes = document.querySelectorAll('.dg-html pre code')
    codes.forEach(el => {
      hljs.highlightElement(el as HTMLElement)
    })
  }, [])

  useEffect(()=>{
    const wrapDOM=wrapRef.current!
    const scrollfn=()=>{
      const rect = authorRef.current?.getBoundingClientRect()!
      if(rect.top <=0){
        setIsShowAuthor(true)
      }else{setIsShowAuthor(false)}
    }
    wrapRef.current?.addEventListener('scroll',scrollfn)
    return ()=>{
      //注销事件 防止内存泄漏
      wrapDOM.removeEventListener('scroll',scrollfn)
    }
  })
  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{article.title}</h1>

            <div className="info">
              <span>{newDayjs(article.pubdate)}</span>
              <span>{article.read_count}阅读</span>
              <span>{article.comm_count}评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src={article.aut_photo} alt="" />
              <span className="name">{article.aut_name}</span>
              <span className={classNames('follow', article.is_followed ? 'followed' : '')}>
                {article.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(article.content || '') }}
            />
            <div className="date">发布文章时间：{newDayjs(article.pubdate)}</div>
          </div>
        </div>

        <div className="comment">
          <div className="comment-header">
            <span>全部评论（10）</span>
            <span>20 点赞</span>
          </div>

          <div className="comment-list">
            {/* <CommentItem /> */}

            <InfiniteScroll
              hasMore={false}
              loadMore={async () => {
                console.log(1)
              }}
            />
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {isShowAuthor && (
          <div className="nav-author">
            <img src={article.aut_photo} alt="" />
            <span className="name">{article.aut_name}</span>
            <span
              className={classNames(
                'follow',
                article.is_followed ? 'followed' : ''
              )}
            >
              {article.is_followed ? '已关注' : '关注'}
            </span>
          </div>
          )}
        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        {/* <CommentFooter /> */}
      </div>
    </div>
  )
}

export default Article
